// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
const db = cloud.database();
// 云函数入口函数
exports.main = async (event, context) => {
  var users = []
  db.collection('subcribe').get().then(res=>{
    users = res.data
  })
  for(let item of users){
    db.collection('message').where(_.or([
      {
        _openid:_.eq(item._openid)
      },
      {
        targetid:_.eq(item._openid)
      }
    ])).get({
      success:function(res){
        var list = res.data
        var num = 0
        for(let listitem of list){
          var len = listitem.content.length
          var i = len - 1
          while(listitem.content[i].openid !== item._openid){
            i--;
            num++;
          }
        }
        if(num > 0){
          wx.showTabBarRedDot({
            index:3
          });
          cloud.openapi.subscribeMessage.send({
            touser: 'oVpE-4z21hVlFScFHcY4QJJSg8nc',
            page: 'pages/message/message',
            data: {
              phrase1:{
                value:'新消息'
              },
              thing2:{
                value:num
              }
            },
            templateId: 't2r26N3WvkUIKJ3eMI1cphObk5T2gb9VuPQBGHx5kec',
          })
        }else{
          wx.hideTabBarRedDot({
            index:3
          })
        }
      }
    })
  }
  
}